package ru.paswd.marketprice.distance.calculator.impl;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import ru.paswd.marketprice.distance.calculator.DistanceCalculator;

@Component
@ConditionalOnProperty(name = "app.distance.calculation.method", havingValue = "spherical")
public class SphericalDistanceCalculator implements DistanceCalculator {

    private static final double EARTH_RADIUS = 6372795.;

    @Override
    public int getDistance(double lat1, double lng1, double lat2, double lng2) {
        double rLat1 = Math.toRadians(lat1);
        double rLng1 = Math.toRadians(lng1);
        double rLat2 = Math.toRadians(lat2);
        double rLng2 = Math.toRadians(lng2);

        double cosLat1 = Math.cos(rLat1);
        double cosLat2 = Math.cos(rLat2);
        double sinLat1 = Math.sin(rLat1);
        double sinLat2 = Math.sin(rLat2);

        double dLng = Math.abs(rLng2 - rLng1);
        double cosDLng = Math.cos(dLng);
        double sinDLng = Math.sin(dLng);

        double y = Math.sqrt(
                Math.pow(cosLat2 * sinDLng, 2) + Math.pow(cosLat1 * sinLat2 - sinLat1 * cosLat2 * cosDLng, 2));
        double x = sinLat1 * sinLat2 + cosLat1 * cosLat2 * cosDLng;

        return Long.valueOf(
                Math.round(
                        Math.atan2(y, x) * EARTH_RADIUS))
                .intValue();
    }
}
